package com.nineclock.system.service.impl;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.entity.UserInfo;

import com.nineclock.common.oss.OssProperties;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.dto.SysUpdataCompanyDto;
import com.nineclock.system.mapper.SysCompanyMapper;
import com.nineclock.system.pojo.SysCompany;
import com.nineclock.system.service.SysCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@Service
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements SysCompanyService {

    @Override
    public SysCompany CompanyMessage() {
        UserInfo userInfo = CurrentUserHolder.get();
        Long id = userInfo.getCompanyId();
        if (userInfo == null) {
            throw new RuntimeException("请登录后重试");
        }
        SysCompany byId = this.getById(id);

        return byId;
    }

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;

    @Override
    public String uploadOss(MultipartFile file) {

        if (file==null){
            throw new RuntimeException("参数错误");
        }
        String filename = file.getOriginalFilename();
        int i= filename.lastIndexOf(".");
        String lastname = filename.substring(i);


        //上传更改后文件名
        String upname = UUID.randomUUID() + lastname;
        //BucketName
        String bucketName = ossProperties.getBucketName();

        try {
            ossClient.putObject(bucketName,upname , file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result=ossProperties.getHost().replace("%s",bucketName)+upname.toString();


        return result;
                }

    @Override
    public void updateCompany(SysUpdataCompanyDto dto) {
        //从ThreadLocal中获取当前登录用户信息,
        UserInfo userInfo = CurrentUserHolder.get();
        //从用户与信息中获取公司id
        Long companyId = userInfo.getCompanyId();
        SysCompany byId = this.getById(companyId);
        //判断在数据库中是否存在
        if (byId==null){
            throw  new RuntimeException("数据不存在");
        }
        SysCompany sysCompany = new SysCompany();
        sysCompany.setId(companyId);
        sysCompany.setName(dto.getName());
        sysCompany.setLogo(dto.getLogo());
        this.updateById(sysCompany);

    }





                }
